//
//  STOrderDetailVC.m
//  YiYueStore
//
//  Created by zhouzhouzhou on 2018/9/28.
//  Copyright © 2018年 YuYiLian. All rights reserved.
//

#import "STOrderDetailVC.h"
#import "STOrderInfoView.h"

#import "STCountDownTimerView.h"
#import "STUserInfoView.h"
#import "STOrderOverView.h"
#import "STOrderPriceOverView.h"
#import "STOrderFooter1View.h"
#import "ChatViewController.h"
#import "MapNavigationTool.h"
#import "STOrderCommentVC.h"
@interface STOrderDetailVC ()<STOrderFooter1ViewDelegate,STOrderOverViewDelegate>
{
    NSString* _amount;
    NSString * _reason;
}
@end

@implementation STOrderDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"我的订单";
    [self wr_setNavBarTintColor:[UIColor blackColor]];
    self.view.autoresizesSubviews = NO;
    [self loadOrderDetailData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//加载数据
-(void)loadOrderDetailData{
    
    NSDictionary * params = @{@"orderId":_detailModel.orderId};
    BasicRequest * request = [[BasicRequest alloc] initWithParams:params];
    request.URL = [NSString stringWithFormat:@"%@stylistOrder/findOrder",BASEURL];
    [request startGetRequestWithSuccess:^(NSURLSessionTask *task, id responseObject) {
        _detailModel = [YLHomeOrderListModel modelWithDictionary:[responseObject objectForKey:@"data"]];
        [self loadOrderView:_detailModel];
    } Failure:nil];
}

//加载页面
-(void)loadOrderView:(id)orderData{
    
    int type =  _orderType;
   
    
    //加载用户信息
    STUserInfoView * userView =  [[NSBundle mainBundle] loadNibNamed:@"STUserInfoView"owner:self options:nil].lastObject;
    userView.frame = CGRectMake(0, 64, SCREEN_WIDTH, 200);
    [userView setUserInfoWithData:_detailModel];
    [self.view addSubview:userView];
    
    //加载服务项目
    STOrderOverView * orderProView = [[STOrderOverView alloc]initWithFrame:CGRectMake(0, userView.bottom, SCREEN_WIDTH, 200)];
    
    [orderProView setOrderOverViewWithType:type data:orderData];
    [self.view addSubview:orderProView];
    orderProView.delegate = self;
    
    //加载其他信息（申请处理，价格说明等）
    STOrderPriceOverView * orderExtraView = [[STOrderPriceOverView alloc]initWithFrame:CGRectMake(0, orderProView.bottom, SCREEN_WIDTH, 250)];
    [orderExtraView setOrderPriceOverWithType:type data:orderData];
    [self.view addSubview:orderExtraView];
    
    
    //加载footer
    STOrderFooter1View * orderFooterView = [[STOrderFooter1View alloc]initWithFrame: CGRectMake(0, SCREEN_HEIGHT-50, SCREEN_WIDTH, 50)];
    [orderFooterView setOrderFooterViewWithType:type data:orderData];
    orderFooterView.footerDelegate = self;
    [self.view addSubview:orderFooterView];
    
    if ([_detailModel.status integerValue] == 13 || [_detailModel.status integerValue] == 3) {
        STCountDownTimerView * timerView = [[STCountDownTimerView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
        [timerView setCountDownNum:360 showString:@"处理订单，超过时间将默认同意..."];
        [self.view addSubview:timerView];
    }
    
//    STOrderInfoView * orderInfoView = [[STOrderInfoView alloc]initWithFrame:self.view.frame];
//    orderInfoView.delegate = self;
//    [orderInfoView setOrderInfoViewWithType:self.orderType withData:orderData];
//    [self.view addSubview:orderInfoView];
//
//    

    
}

-(int)getOrderTypeFromData:(id)data{
    return self.orderType;
}

-(void)STOrderOverViewGetAddress{
    [MapNavigationTool startMapNavigationWithViewController:self Latitude:[_detailModel.storeLocation.latitude floatValue] Longitude:[_detailModel.storeLocation.longitude floatValue]];
}
-(void)orderFooter1ViewWithActionType:(STOrderFooter1ViewActionType)actionType orderType:(int)orderType{
    if (actionType == telBtnAction) {
        [self callPhone];
    }else if (actionType == msgBtnAction) {
        [self sendMessage];
    }else if (actionType == agreeBtnAction) {
        if ([_detailModel.status integerValue] == 13) {
            [self cancelOrderWithIsArgee:YES];
        }else if ([_detailModel.status integerValue] == 8) {
            [self addMoney:YES];
        }else if ([_detailModel.status integerValue] == 3) {
            [self receveOrder:YES];
        }else if ([_detailModel.status integerValue] == 4) {
            [self startService:YES];
        }else if ([_detailModel.status integerValue] == 7) {
            [self completeService:YES];
        }else if ([_detailModel.status integerValue] == 11) {
//            [self evaluate:YES];
            [self turnToSeeEvaluate];
        }else if ([_detailModel.status integerValue] == 18) {
            //查看评价
            [self turnToSeeEvaluate];
        }
    }else if (actionType == refuseBtnAction) {
        if ([_detailModel.status integerValue] == 13) {
            [self cancelOrderWithIsArgee:NO];
        }else if ([_detailModel.status integerValue] == 8) {
            [self addMoney:NO];
        }else if ([_detailModel.status integerValue] == 3) {
            [self receveOrder:NO];
        }else if ([_detailModel.status integerValue] == 4) {
            [self startService:NO];
        }else if ([_detailModel.status integerValue] == 7) {
            [self completeService:NO];
        }
    }
}
-(void)callPhone{
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    webView.hidden = YES;
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",_detailModel.userMobile]];
    [webView loadRequest:[NSURLRequest requestWithURL:url ]];
    [self.view addSubview:webView];
}
-(void)sendMessage{
    ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:_detailModel.userImusername conversationType:EMConversationTypeChat];
    chatController.title = _detailModel.userImusername;
    [self.navigationController pushViewController:chatController animated:YES];
}
-(void)cancelOrderWithIsArgee:(BOOL)isArgee{
    NSString * status = isArgee?@"1":@"2";
    BasicRequest * requset = [[BasicRequest alloc] initWithParams:@{@"orderId":_detailModel.orderId,@"status":status}];
    requset.URL = [NSString stringWithFormat:@"%@stylistOrder/agreeCancelOrder",BASEURL];
    [requset startGetRequestWithSuccess:^(NSURLSessionTask *task, id responseObject) {
        [YLProgressHUDManager showMessage:isArgee?@"已经同意取消订单":@"已经拒绝取消订单"];
    } Failure:nil];
}
-(void)addMoney:(BOOL)isAdd{
    if (isAdd) {
        BasicRequest * requset = [[BasicRequest alloc] initWithParams:@{@"orderId":_detailModel.orderId,@"status":@"1"}];
        requset.URL = [NSString stringWithFormat:@"%@stylistOrder/remindReviews",BASEURL];
        [requset startGetRequestWithSuccess:^(NSURLSessionTask *task, id responseObject) {
            [YLProgressHUDManager showMessage:@"发送提醒成功"];
        } Failure:nil];
    }else{
        BasicRequest * requset = [[BasicRequest alloc] initWithParams:@{@"orderId":_detailModel.orderId}];
        requset.URL = [NSString stringWithFormat:@"%@stylistOrder/cancelAddmoneyRequest",BASEURL];
        [requset startGetRequestWithSuccess:^(NSURLSessionTask *task, id responseObject) {
            [YLProgressHUDManager showMessage:@"取消成功"];
        } Failure:nil];
    }
}
-(void)receveOrder:(BOOL)isArgee{
    if (isArgee) {
        BasicRequest * requset = [[BasicRequest alloc] initWithParams:@{@"orderId":_detailModel.orderId}];
        requset.URL = [NSString stringWithFormat:@"%@stylistOrder/acceptOrder",BASEURL];
        [requset startGetRequestWithSuccess:^(NSURLSessionTask *task, id responseObject) {
            [YLProgressHUDManager showMessage:@"接受订单成功"];
        } Failure:nil];
    }else{
        BasicRequest * requset = [[BasicRequest alloc] initWithParams:@{@"orderId":_detailModel.orderId}];
        requset.URL = [NSString stringWithFormat:@"%@stylistOrder/refuseOrder",BASEURL];
        [requset startGetRequestWithSuccess:^(NSURLSessionTask *task, id responseObject) {
            [YLProgressHUDManager showMessage:@"已经拒绝订单"];
        } Failure:nil];
    }
}
-(void)startService:(BOOL)isStart{
    if (isStart) {
        
        int hours = [NSString getTodayDistanceDataWithTime:_detailModel.ordertime]/3600;
        NSString * message;
        if (hours<8) {
            message = [NSString stringWithFormat:@"当前时间已超过订单无责任取消有效期，强制取消预约将扣除订单价格%@%%手续费返还给用户等价的平台通用抵扣券，是否确认取消该订单？",@""];
        }else{
            message = @"是否确认取消该订单?";
        }
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
             [self sendStartServiceRequest];
        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action1];
        [alert addAction:action2];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        [self sendCancelOrderRequest];
    }
}
-(void)completeService:(BOOL)isComplete{
    if (isComplete) {
        int seconds = [NSString getTodayDistanceDataWithTime:_detailModel.starttime];
        int hours = seconds/3600;
        int minnutes = (seconds%3600)/60;
        NSString * message = [NSString stringWithFormat:@"该订单已服务%d小时%d分，请确认是否已完成该服务？",hours,minnutes];
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"完成订单提示" message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self sendCompleteServiceRequest];
        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action1];
        [alert addAction:action2];
        [self presentViewController:alert animated:YES completion:nil];
        
    }else{
        NSString * message = [NSString stringWithFormat:@"加价前请与顾客协商好，顾客有权拒绝您的加价"];
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"加价提示" message:message preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            _amount = alert.textFields.firstObject.text;
            _reason = alert.textFields.lastObject.text;
            [self sendAddMoneyRequest];
        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action1];
        [alert addAction:action2];
        [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.leftView = [self getLeftLabWithText:@"金额"];
            textField.placeholder = @"请输入加价金额";
        }];
        
        [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            textField.leftView = [self getLeftLabWithText:@"原因"];
            textField.placeholder = @"请输入加价原因";
        }];

        [self presentViewController:alert animated:YES completion:nil];
    }
}
-(UILabel*)getLeftLabWithText:(NSString*)text{
    UILabel * lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 50, 35)];
    lab.text = text;
    lab.font = FONT(15);
    lab.textColor = BlackColor;
    return lab;
}
-(void)evaluate:(BOOL)isInvete{
    if (isInvete) {
        BasicRequest * requset = [[BasicRequest alloc] initWithParams:@{@"orderId":_detailModel.orderId,@"status":@"2"}];
        requset.URL = [NSString stringWithFormat:@"%@stylistOrder/remindReviews",BASEURL];
        [requset startGetRequestWithSuccess:^(NSURLSessionTask *task, id responseObject) {
            [YLProgressHUDManager showMessage:@"邀请成功"];
        } Failure:nil];
    }else{
        
    }
}

-(void)turnToSeeEvaluate{
    STOrderCommentVC * commentVC = [STOrderCommentVC new];
    commentVC.detailModel = _detailModel;
    commentVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:commentVC animated:NO];
}


-(void)sendCancelOrderRequest{
    BasicRequest * requset = [[BasicRequest alloc] initWithParams:@{@"orderId":_detailModel.orderId}];
    requset.URL = [NSString stringWithFormat:@"%@stylistOrder/cancelOrder",BASEURL];
    [requset startGetRequestWithSuccess:^(NSURLSessionTask *task, id responseObject) {
        [YLProgressHUDManager showMessage:@"取消成功"];
    } Failure:nil];
}
-(void)sendStartServiceRequest{
    BasicRequest * requset = [[BasicRequest alloc] initWithParams:@{@"orderId":_detailModel.orderId}];
    requset.URL = [NSString stringWithFormat:@"%@stylistOrder/startOrder",BASEURL];
    [requset startGetRequestWithSuccess:^(NSURLSessionTask *task, id responseObject) {
        [YLProgressHUDManager showMessage:@"开始服务成功"];
    } Failure:nil];
}
-(void)sendCompleteServiceRequest{
    BasicRequest * requset = [[BasicRequest alloc] initWithParams:@{@"orderId":_detailModel.orderId}];
    requset.URL = [NSString stringWithFormat:@"%@stylistOrder/completeOrder",BASEURL];
    [requset startGetRequestWithSuccess:^(NSURLSessionTask *task, id responseObject) {
        [YLProgressHUDManager showMessage:@"完成服务成功"];
    } Failure:nil];
}
-(void)sendAddMoneyRequest{
    BasicRequest * requset = [[BasicRequest alloc] initWithParams:@{@"orderId":_detailModel.orderId,@"adddesc":_reason,@"addmoney":_amount}];
    requset.URL = [NSString stringWithFormat:@"%@stylistOrder/addMoneyRequest",BASEURL];
    requset.requestMethod = HttpRequestMethodRawPOST;
    [requset startRequestWithSuccess:^(NSURLSessionTask *task, id responseObject) {
        [YLProgressHUDManager showMessage:@"加价成功"];
    } Failure:nil];
}
@end
